﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace detect
{
    public partial class myForm : Form
    {
        SqlConnection connect = new SqlConnection();
        SqlCommand command = new SqlCommand();

        //学校阳光广场为学校中心点
        static double latitude = 29.8113575; //纬度
        static double longitude = 121.5653151; //经度

        public delegate void OutDelegate(string text);
        public void OutText(string text)
        {
            tbMessage.AppendText(text);
        }
        public myForm()
        {
            InitializeComponent();
        }

        private void bStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (!timer.Enabled)
                {
                    connect.ConnectionString = "server=172.18.0.88;database=pro;user=sa;pwd=comefirst@503";
                    timer.Enabled = true;
                    btStart.Text = " 正在定位";
                    timer_Tick(sender,e);
                    timer.Interval = Convert.ToInt16(tbDelay.Text) * 1000;
                }
                else
                {
                    timer.Enabled = false;
                    btStart.Text = "开始定位";
                }
            }
            catch(Exception exception)
            {
                writeLog(exception.Message);
            }
        }
       

        //触发器开始一个新线程
        private void timer_Tick(object sender, EventArgs e)
        {
            Thread th = new Thread(getPosition);
            th.IsBackground = true;
            th.Start();
        }

        //获取定位信息
        void getPosition()
        {
            try
            {
                IPAddress ip; //IP地址
                int port;  //端口号
                byte[] result = new byte[1024];   //返回内容

                Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ip = IPAddress.Parse(tbServer.Text);
                port = Convert.ToInt32(tbPort.Text);
                clientSocket.Connect(new IPEndPoint(ip, port));
                string text = "开始定位\r\n";
                OutDelegate outdelegate = new OutDelegate(OutText);
                this.BeginInvoke(outdelegate, new object[] { text });

                string sendMessage = "<account>" + tbAccount.Text + "</account><password>"
                        + tbPassword.Text + "</password><result_type>9</result_type><msids>"
                        + getPhonesFromDataBase() + "</msids>\n";
                clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));

                int receiveLength = clientSocket.Receive(result);
                string my = Encoding.GetEncoding("GB2312").GetString(result, 0, receiveLength);
                insertPositionToDataBase(my);
                this.BeginInvoke(outdelegate, new object[] { my });
            }
            catch (Exception exception)
            {
                writeLog(exception.Message);
            }
        }

        //从数据库中读取电话号码，返回手机长号字符串，多个号码以逗号间隔，并更新时间。
        string getPhonesFromDataBase()
        {
            string phones="";
            string teachers = "";
            try
            {
                string sql = "select top 1 teacherno,phone from teacher order by date ";
                connect.Open();
                command.Connection = connect;
                command.Connection = connect;
                command.CommandType = CommandType.Text;
                command.CommandText = sql;
                SqlDataReader read = command.ExecuteReader();
                while (read.Read())
                {
                    read["teacherno"].ToString();
                    phones = phones + read["phone"].ToString() + ",";
                    string teacher_one = String.Format("'{0}',",read["teacherno"].ToString());
                    teachers = teachers + teacher_one;
                }
                connect.Close();
                phones = phones.Substring(0, phones.Length - 1);
                teachers = teachers.Substring(0, teachers.Length - 1);
                sql = "update teacher set date=getdate() where teacherno in (" + teachers+")";
                command.CommandText = sql;
                connect.Open();
                command.ExecuteNonQuery();
                connect.Close();
               
            }
            catch (Exception exception)
            {
                writeLog(exception.Message);
            }
            return phones;
        }

        //把定位数据插入数据库
        void insertPositionToDataBase(string result)
        {
            try
            {
                string[] result_array = result.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); //化成多个行
                string sql = "insert into location(type,phone,longitude,latitude,description,date,distance) values ";
                int len = result_array.Length;
                for (int i = 0; i < len; i++)
                {
                    string one = result_array[i];
                    string[] one_array = one.Split('/');
                    int distance = 0;
                    if(one_array[2]!=""){
                        double dis =Math.Sqrt(Math.Pow((Convert.ToDouble(one_array[2]) - longitude) * 111322, 2) + Math.Pow((Convert.ToDouble(one_array[3]) - latitude) * 100000, 2));
                        distance = Convert.ToInt16(dis);
                    }
                    string values = String.Format("('{0}','{1}','{2}','{3}','{4}','{5}','{6}'),", one_array[0], one_array[1], one_array[2], one_array[3], one_array[4], one_array[5],distance);
                    sql = sql + values;
                }
                sql = sql.Substring(0, sql.Length - 1);
                connect.Open();
                command.Connection = connect;
                command.CommandType = CommandType.Text;
                command.CommandText = sql;
                command.ExecuteNonQuery();
                connect.Close();

            }
            catch (Exception exception)
            {
                writeLog(exception.Message);
            }

        }

        void writeLog(string message)
        {
            try
            {
                string path = Environment.CurrentDirectory + "\\log";
                if (!Directory.Exists(path))//判断是否有该文件夹              
                    Directory.CreateDirectory(path);
                string logFileName = path + "\\Analysis.log";//生成日志文件  
                if (!File.Exists(logFileName))//判断日志文件是否为当天  
                    File.Create(logFileName).Close();//创建文件  

                StreamWriter writer = File.AppendText(logFileName);//文件中添加文件流  
                writer.WriteLine("");
                writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + message);
                writer.Flush();
                writer.Close();
            }
            catch (Exception e)
            {
               
            }  
        }


    }


}
